package com.dg.river.core.http;

import android.content.Context;

import com.dg.river.contant.Constant;
import com.dg.river.core.manager.UserInfoManager;
import com.dg.river.core.manager.UserInfoMethod;
import com.dg.river.core.util.NetUtils;
import com.dg.river.core.util.TextUtil;
import com.dg.river.core.util.Utils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.DeleteRequest;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * @作者：Hututu
 * @时间：2023/4/6 9:53
 * @描述：内容描述
 * @修改：修改内容
 * @Version:1.0
 */
public class OkGoUtils {

    private Context mContext;

    // 请求地址
    private String url;
    // 请求描述
    private String tag;
    // 自定义请求头
    private HttpHeaders httpHeaders;
    // 接口版本号
    private String version;
    // 设备token
    private boolean deviceToken;
    // 用户token
    private boolean userToken;
    // 参数Map集合
    private Map<String, Object> paramsMap;
    // 参数转Json后UpJsonMap集合
    private Map<String, Object> paramsToJsonMap;
    // 上传文件的Key
    private String fileListKey;
    // 上传文件数组
    private List<File> fileList;

    public static OkGoUtils okGoUtils;

    public static OkGoUtils getInstance() {
        if (okGoUtils == null) {
            synchronized (OkGoUtils.class) {
                okGoUtils = new OkGoUtils();
            }
        }
        return okGoUtils;
    }

    /**
     * 初始化
     *
     * @param mContext
     */
    public void init(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 设置请求地址
     *
     * @param url
     * @return
     */
    public OkGoUtils url(String url) {
        this.url = url;
        return this;
    }

    /**
     * 设置请求描述
     *
     * @param tag
     * @return
     */
    public OkGoUtils tag(String tag) {
        this.tag = tag;
        return this;
    }

    /**
     * 设置接口版本号
     *
     * @param version
     * @return
     */
    public OkGoUtils version(String version) {
        this.version = version;
        return this;
    }

    /**
     * 设置设备token
     *
     * @return
     */
    public OkGoUtils deviceToken() {
        this.deviceToken = true;
        return this;
    }

    /**
     * 设置用户token
     *
     * @return
     */
    public OkGoUtils userToken() {
        this.userToken = true;
        return this;
    }

    /**
     * 设置自定义请求头
     *
     * @param httpHeaders
     * @return
     */
    public OkGoUtils httpHeaders(HttpHeaders httpHeaders) {
        this.httpHeaders = httpHeaders;
        return this;
    }

    /**
     * 设置一般参数Map集合
     *
     * @param paramsMap
     * @return
     */
    public OkGoUtils paramsMap(Map<String, Object> paramsMap) {
        this.paramsMap = paramsMap;
        return this;
    }

    /**
     * 设置参数转Json后UpJsonMap集合
     *
     * @param paramsToJsonMap
     * @return
     */
    public OkGoUtils paramsToJsonMap(Map<String, Object> paramsToJsonMap) {
        this.paramsToJsonMap = paramsToJsonMap;
        return this;
    }

    /**
     * 设置上传文件
     *
     * @param fileListKey
     * @param fileList
     * @return
     */
    public OkGoUtils listFile(String fileListKey, List<File> fileList) {
        this.fileListKey = fileListKey;
        this.fileList = fileList;
        return this;
    }

    /**
     * 执行Get网络请求
     */
    public void executeGet(OnResultListener onResultListener) {
        if (NetUtils.isNetworkAvailable(mContext)) {
            GetRequest<String> request;
            if (!TextUtil.isEmpty(url)) {
                request = OkGo.get(url);
            } else {
                throw new RuntimeException("请检查请求地址是否正确");
            }
            if (!TextUtil.isEmpty(tag)) {
                request.tag(tag);
            } else {
                request.tag("暂未填写请求描述");
            }
            if (userToken) {
                request.headers(Constant.AuthorizationKey, UserInfoManager.getInstance().userToken(UserInfoMethod.GET, "", true));
            }
            if (deviceToken) {
                request.headers(Constant.AuthorizationKey, UserInfoManager.getInstance().tripToken(UserInfoMethod.GET, "", true));
            }
            if (httpHeaders != null) {
                request.headers(httpHeaders);
            }
            request.headers("version", TextUtil.isEmpty(version) ? "v1" : version);
            if (paramsMap != null) {
                for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
                    request.params(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            if (paramsToJsonMap != null) {
                throw new RuntimeException("GET请求无法传递Json，请使用Post方法");
            }
            if (fileList != null) {
                throw new RuntimeException("GET请求无法上传文件，请使用Post方法");
            }
            // 清空上次请求信息
            cleanRequestInfo();
            // 发起请求
            request.execute(getStringCallBack(onResultListener));
        } else {
            if (onResultListener != null) {
                onResultListener.onError(RequestCodeEnum.NETWORK_EXCEPTION, null);
            }
        }
    }

    /**
     * 执行Post网络请求
     */
    public void executePost(OnResultListener onResultListener) {
        if (NetUtils.isNetworkAvailable(mContext)) {
            PostRequest<String> request;
            if (!TextUtil.isEmpty(url)) {
                request = OkGo.post(url);
            } else {
                throw new RuntimeException("请检查请求地址是否正确");
            }
            if (!TextUtil.isEmpty(tag)) {
                request.tag(tag);
            } else {
                request.tag("暂未填写请求描述");
            }
            if (userToken) {
                request.headers(Constant.AuthorizationKey, UserInfoManager.getInstance().userToken(UserInfoMethod.GET, "", true));
            }
            if (deviceToken) {
                request.headers(Constant.AuthorizationKey, UserInfoManager.getInstance().tripToken(UserInfoMethod.GET, "", true));
            }
            if (httpHeaders != null) {
                request.headers(httpHeaders);
            }
            request.headers("version", TextUtil.isEmpty(version) ? "v1" : version);
            if (paramsMap != null) {
                for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
                    request.params(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            if (paramsToJsonMap != null) {
                request.upJson(Utils.mapToJson(paramsToJsonMap));
            }
            if (fileList != null) {
                request.addFileParams(fileListKey, fileList);
            }
            // 清空上次请求信息
            cleanRequestInfo();
            // 发起请求
            request.execute(getStringCallBack(onResultListener));
        } else {
            if (onResultListener != null) {
                onResultListener.onError(RequestCodeEnum.NETWORK_EXCEPTION, null);
            }
        }
    }

    /**
     * 执行Delete网络请求
     */
    public void executeDelete(OnResultListener onResultListener) {
        if (NetUtils.isNetworkAvailable(mContext)) {
            DeleteRequest<String> request;
            if (!TextUtil.isEmpty(url)) {
                request = OkGo.delete(url);
            } else {
                throw new RuntimeException("请检查请求地址是否正确");
            }
            if (!TextUtil.isEmpty(tag)) {
                request.tag(tag);
            } else {
                request.tag("暂未填写请求描述");
            }
            if (userToken) {
                request.headers(Constant.AuthorizationKey, UserInfoManager.getInstance().userToken(UserInfoMethod.GET, "", true));
            }
            if (deviceToken) {
                request.headers(Constant.AuthorizationKey, UserInfoManager.getInstance().tripToken(UserInfoMethod.GET, "", true));
            }
            if (httpHeaders != null) {
                request.headers(httpHeaders);
            }
            request.headers("version", TextUtil.isEmpty(version) ? "v1" : version);
            if (paramsMap != null) {
                for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
                    request.params(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            if (paramsToJsonMap != null) {
                throw new RuntimeException("DELETE请求无法传递Json，请使用Post方法");
            }
            if (fileList != null) {
                throw new RuntimeException("DELETE请求无法上传文件，请使用Post方法");
            }
            // 清空上次请求信息
            cleanRequestInfo();
            // 发起请求
            request.execute(getStringCallBack(onResultListener));
        } else {
            if (onResultListener != null) {
                onResultListener.onError(RequestCodeEnum.NETWORK_EXCEPTION, null);
            }
        }
    }

    /**
     * 获取请求回调StringCallBack
     *
     * @return
     */
    private StringCallback getStringCallBack(OnResultListener onResultListener) {
        return new StringCallback() {

            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                if (onResultListener != null) {
                    onResultListener.onLoading();
                }
            }

            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                if (onResultListener != null) {
                    onResultListener.onSuccess(body);
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (onResultListener != null) {
                    onResultListener.onError(RequestCodeEnum.ERROR_EXCEPTION, getErrorMsg(response));
                }
            }
        };
    }

    /**
     * 清空上次请求信息
     */
    private void cleanRequestInfo() {
        url = null;
        tag = null;
        httpHeaders = null;
        version = "v1";
        deviceToken = false;
        userToken = false;
        paramsMap = null;
        paramsToJsonMap = null;
        fileListKey = null;
        fileList = null;
    }

    /**
     * 获取错误信息
     *
     * @param response
     * @return
     */
    private String getErrorMsg(Response<String> response) {
        String errorMsg = "";
        if (response.getRawResponse() != null) {
            errorMsg += "===== 错误原因 RawResponse：" + response.getRawResponse().toString() + " =====\n";
        } else {
            errorMsg += "===== 错误原因 RawResponse：未知 =====\n";
        }
        if (response.getException() != null) {
            errorMsg += "===== 错误原因 Exception：" + response.getException().toString() + " =====";
        } else {
            errorMsg += "===== 错误原因 Exception：未知 =====";
        }
        return errorMsg;
    }
}
